package org.pb.visit.basic.interceptor;

import org.pb.visit.domain.Visitor;
import org.pb.visit.mapper.VisitorMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 远端访问拦截器
 * @author
 */
@Component
public class VisitInterceptor implements HandlerInterceptor {

    @Autowired
    private VisitorMapper visitorMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String addr = request.getRemoteAddr();
        final String local = "0:0:0:0:0:0:0:1";
        final String local1 = "127.0.0.1";
        final String local2 = "localhost";
        // 如果访问项目的ip地址不是本机，就将其添加到数据库的访问者表中
        if (!local.equals(addr) && !local1.equals(addr) && !local2.equals(addr)) {
            // 将该地址添加到访问者表中
            Visitor visitor = new Visitor();
            visitor.setAddress(addr);
            visitorMapper.save(visitor);
            System.err.println(addr);
        }
        // 设置拦截ip字符串
        final String addr1 = "172.16.4.97";
        final String addr2 = "172.16.4.103";
        final String addr3 = "175.16.4.50";
        // 因为addr可能为null，所以需要用目标字符串进行equals判断。如果和目标ip字符串地址值一样，拦截
        if (addr1.equals(addr) || addr2.equals(addr) || addr3.equals(addr)) {
            return false;
        }
        // 其他ip放行
        return true;
    }
}
